<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\common\Pay;
use app\common\Sms;
use app\common\UserService;
use app\job\Task;
use app\model\Goods;
use app\model\GoodsOrders;
use app\model\GoodsOrdersAssess;
use app\model\User;
use app\tool\Random;
use think\db\Query;
use think\facade\Db;
use think\facade\Queue;
use think\facade\Validate;

class GoodsController extends BaseController
{
	function index()
	{
		$rows = Goods::order(['id' => 'desc'])
			->with(['spec'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	
	function detail()
	{
		$goods_id = $this->request->get('goods_id/d');
		$row = Goods::with(['user_collect' => function (Query $query) {
			$query->where('user_id', $this->user_id);
		}, 'spec'])->findOrFail($goods_id);
		$this->writeJson($row);
	}
	
	function collect()
	{
		$goods_id = $this->request->post('goods_id/d');
		$ret = UserService::collect($goods_id, $this->user_id, 1);
		$this->writeJson($ret);
	}
	
	function createOrder()
	{
		$goods_id = $this->request->post('goods_id/d'); //商品
		$address_id = $this->request->post('address_id/d');
		$mark = $this->request->post('mark', '');
		$goods = Goods::findOrFail($goods_id);
		if (empty($address_id)) {
			$this->writeJson(0, '请选择收货地址');
		}
		$pay_amount = $goods->spec->price;
		$ordersn = Random::ordersn();
		
		$data = [
			'address_id' => $address_id,
			'user_id' => $this->user_id,
			'order_sn' => $ordersn,
			'pay_amount' => $pay_amount,
			'mark' => $mark
		];
		// 启动事务
		Db::startTrans();
		try {
			$order = GoodsOrders::create($data);
			$order->detail()->save([
				'goods_id' => $goods_id,
				'amount' => $goods->spec->price,
				'spec_id' => $goods->spec->id
			]);
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			$this->writeJson(0, $e->getMessage());
		}
		Queue::later(60 * 15, Task::class, ['order_id' => $order->id, 'action' => 'goods_order_timeout'], 'task');
		$this->writeJson($order);
	}
	
	function orderPay()
	{
        $order_id = $this->request->post('order_id/d');
		$pay_type = $this->request->post('pay_type/d');
		$row = GoodsOrders::where(['user_id' => $this->user_id, 'status' => 1])->findOrFail($order_id);
		$user = User::findOrFail($this->user_id);
		// 启动事务
		Db::startTrans();
		try {
			if (in_array($pay_type, [1, 2])) {
				$ret = Pay::pay($pay_type, $row->pay_amount, $row->order_sn, '购买商品', 'goods', $user->openid);
			} else {
				UserService::changeUserMoney(-$row->pay_amount, $user->id, '购买商品');
				app(NotifyController::class)->returnNotify(request()->setRoute(['paytype' => 'balance', 'out_trade_no' => $row->order_sn, 'attach' => 'goods']));
				$ret = true;
			}
            $row->pay_source = request()->header('Client');
			$row->pay_type = $pay_type;
			$row->save();
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			$this->writeJson(0, $e->getMessage());
		}
		$this->writeJson($ret);
	}
	
	function getAssessList()
	{
		$goods_id = $this->request->get('goods_id/d');
		$type = $this->request->get('type/d');
		$rows = GoodsOrdersAssess::where(['goods_id' => $goods_id])
			->with(['user'])
			->when(!empty($type), function (Query $query) use ($type) {
				if ($type == 1) {
					$query->where('score', 5);
				}
				if ($type == 2) {
					$query->whereBetween('score', [2, 4]);
				}
				if ($type == 3) {
					$query->where('score', 1);
				}
				if ($type == 4) {
					$query->where('images', '<>', '');
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		foreach ($rows as $row){
			if ($row->anonymous == 1){
				$row->user->nickname = '匿名';
			}
		}
		$assess_count = GoodsOrdersAssess::where(['goods_id' => $goods_id])->count();//总数
		$good_count = GoodsOrdersAssess::where(['goods_id' => $goods_id])->where('score', 5)->count();//好评
		$just_count = GoodsOrdersAssess::where(['goods_id' => $goods_id])->whereBetween('score', [2, 4])->count();//中评
		$bad_count = GoodsOrdersAssess::where(['goods_id' => $goods_id])->where('score', 1)->count();//差评
		$images_count = GoodsOrdersAssess::where(['goods_id' => $goods_id])->where('images', '<>', '')->count();//有图
		$this->writeJson(['count' => $assess_count, 'good_count' => $good_count, 'just_count' => $just_count, 'bad_count' => $bad_count, 'images_count' => $images_count, 'list' => $rows]);
	}
	
	
	/**
	 * 订单列表
	 * @return void
	 */
	function orderList()
	{
		$status = $this->request->get('status/d'); // 状态： 0全部 1待付款 2待发货 3待收货 4已完成
		$rows = GoodsOrders::where(['user_id' => $this->user_id])
			->with(['detail' => function (Query $query) {
				$query->with(['goods', 'spec']);
			}])
			->when(!empty($status), function (Query $query) use ($status) {
				switch ($status) {
					case 1:
						$query->where(['status' => 1]);
						break;
					case 2:
						$query->where(['status' => 2]);
						break;
					case 3:
						$query->where(['status' => 3]);
						break;
					case 4:
						$query->whereIn('status', [4, 5]);
						break;
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		$this->writeJson($rows);
	}
	
	#订单详情
	function orderDetail()
	{
		$order_id = $this->request->get('order_id/d');
		$row = GoodsOrders::where(['user_id' => $this->user_id, 'id' => $order_id])
			->with(['detail' => function (Query $query) {
				$query->with(['goods', 'spec']);
			}, 'address'])
			->findOrFail();
		$this->writeJson($row);
	}
	
	
	#取消订单
	function orderCancel()
	{
		$order_id = $this->request->post('order_id/d');
		$row = GoodsOrders::where(['user_id' => $this->user_id, 'id' => $order_id, 'status' => 1])->findOrFail();
		$row->status = 6;
		$row->save();
		$this->writeJson();
	}
	
	/**
	 * 订单删除
	 * @return void
	 */
	function orderDelete()
	{
		$order_id = $this->request->post('order_id/d');
		$row = GoodsOrders::where(['user_id' => $this->user_id, 'id' => $order_id])->whereIn('status', [5, 6])->findOrFail();
		$row->delete();
		$this->writeJson();
	}
	
	#确认收货
	function orderConfirm()
	{
		$order_id = $this->request->post('order_id/d');
		$row = GoodsOrders::where(['user_id' => $this->user_id, 'id' => $order_id])->whereIn('status', [3])->findOrFail();
		$row->status = 4;
		$row->confirmtime = time();
		$row->save();
		$this->writeJson();
	}
	
	function orderAssess()
	{
		$anonymity = $this->request->post('anonymity/d'); #匿名:1=是,2=否
		$order_id = $this->request->post('order_id/d');
		$assess = $this->request->post('assess/a');#评价内容 [{"order_detail_id":"xx“,"goods_id":"xxx","score":"xxx","images":"xxxx","content":"xx"}]
		if (empty($assess) || empty($anonymity)) {
			$this->writeJson(0, '参数错误');
		}
		$order = GoodsOrders::where(['user_id' => $this->user_id, 'id' => $order_id, 'status' => 4])->findOrFail();
		foreach ($assess as $item) {
			$item['user_id'] = $this->user_id;
			GoodsOrdersAssess::create($item);
		}
		$order->status = 5;
		$order->save();
		$this->writeJson();
	}
	
	
}
